package com.glory.wxmemsicpda.adapter

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.chad.library.adapter.base.BaseQuickAdapter
import com.glory.wxmemsicpda.R
import com.glory.wxmemsicpda.base.DataBindBaseViewHolder
import com.glory.wxmemsicpda.bean.EqpListBean
import com.glory.wxmemsicpda.bean.SheetInfoBean
import com.glory.wxmemsicpda.callback.SuccessCallback
import com.glory.wxmemsicpda.databinding.AdapterWorkEndFailOutBinding
import java.util.*
import kotlin.collections.ArrayList

class WorkEndFailOutAdapter(data: List<EqpListBean?>?,val callback: SuccessCallback) :
    BaseQuickAdapter<EqpListBean?, DataBindBaseViewHolder>(
        R.layout.adapter_work_end_fail_out,
        data as MutableList<EqpListBean?>
    ) {
    val list: ArrayList<EqpListBean?> = ArrayList()
    override fun convert(helper: DataBindBaseViewHolder, item: EqpListBean?) {
        val binding: AdapterWorkEndFailOutBinding =
            helper.getDataBinding() as AdapterWorkEndFailOutBinding
        binding.entity = item
        binding.executePendingBindings()
        binding.cbCheckAllBadCode.setOnClickListener {
            if (binding.cbCheckAllBadCode.isChecked) {
                item!!.checked = true
                list.add(item)
            }else{
                item!!.checked = false
                list.remove(item)
            }
        }
        binding.cbCheckAllBadCode.isChecked = item!!.checked == true
        setEditListener(binding.etLotId)
    }

    private fun setEditListener(
        editText: EditText,
    ) {
        if (editText.tag is TextWatcher) {
            editText.removeTextChangedListener(editText.tag as TextWatcher);
        }

        var textWatcher: TextWatcher = object : TextWatcher {

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                callback.change()
            }

            override fun afterTextChanged(s: Editable) {
            }
        }
        editText.addTextChangedListener(textWatcher);
        editText.tag = textWatcher;
    }

    fun getDeleteData() : ArrayList<EqpListBean?> {
        return list
    }

    fun setData(nRejectCodes: MutableList<EqpListBean?>?) {
        if (nRejectCodes != null) {
            data = nRejectCodes
            notifyDataSetChanged()
        }
    }

    //设置全选
    fun setAllChecked(isAllChecked: Boolean){
        for (it in data){
            it!!.checked = isAllChecked
        }

        if (isAllChecked){
            list.addAll(data)
        }else{
            if (list.isNotEmpty()){
                list.clear()
            }
        }

        notifyDataSetChanged()
    }
}